package com.shm.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.Picture;
import com.ruoyi.common.core.domain.entity.Product;
import com.ruoyi.common.core.domain.entity.ProductRead;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.vo.ProductVo;
import com.ruoyi.common.enums.ErrorCode;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import com.shm.dataValidate.ProductValidate;
import com.shm.service.IPictureService;
import com.shm.service.IProductReadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.shm.service.IProductService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 商品Controller
 *
 * @author dam
 * @date 2023-07-21
 */
@Api("商品管理")
@RestController
@RequestMapping("/market/product")
public class ProductController extends BaseController {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IProductService productService;
    @Autowired
    private IPictureService pictureService;
    @Autowired
    private IProductReadService productReadService;

    /**
     * 查询商品列表
     */
    @PreAuthorize("@ss.hasPermi('market:product:list')")
    @GetMapping("/list")
    @ApiOperation("获取商品列表")
    public TableDataInfo list(Product product) {
        startPage();
        List<Product> list = productService.selectProductList(product);
        return getDataTable(list);
    }

    /**
     * 查询商品Vo列表
     */
    @PreAuthorize("@ss.hasPermi('market:product:list')")
    @PostMapping("/listProductVo")
    @ApiOperation("获取商品列表")
    public AjaxResult listProductVo(@RequestBody ProductVo productVo) {

        if (productVo.getProductCategoryId() != null) {
            // --if-- 当分类不为空的时候，只按照分类来搜索
            productVo.setKeyword(null);
        }
        if (productVo.getIsSearchStar() != null && productVo.getIsSearchStar() == true) {
            productVo.setStarPeopleId(getLoginUser().getUserId());
        }
        LoginUser loginUser = getLoginUser();
        SysUser sysUser = userService.selectUserById(loginUser.getUserId());
        productVo.setCampusId(sysUser.getCampusId());
        startPage();
        List<ProductVo> productVoList = productService.selectProductVoList(productVo);
        Map<String, Object> map = new HashMap<>();
        TableDataInfo pageMes = getDataTable(productVoList);
        map.put("pageMes", pageMes);
        if (productVo.getSumAspectRatioOfColumn1() != null && productVo.getSumAspectRatioOfColumn2() != null) {
            // 将productVoList分成两组，要求两组的高度之和相差最小
            List<ProductVo>[] groups = productService.splitToTwoGroups(productVoList, productVo.getSumAspectRatioOfColumn1(), productVo.getSumAspectRatioOfColumn2(), productVo.getMessageAspectRatio());
            map.put("groups", groups);
        }

        return AjaxResult.success(map);
    }

    /**
     * 导出商品列表
     */
    @PreAuthorize("@ss.hasPermi('market:product:export')")
    @Log(title = "商品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Product product) {
        List<Product> list = productService.selectProductList(product);
        ExcelUtil<Product> util = new ExcelUtil<Product>(Product.class);
        util.exportExcel(response, list, "商品数据");
    }

    /**
     * 获取商品详细信息
     */
    @PreAuthorize("@ss.hasPermi('market:product:query')")
    @GetMapping(value = "/{id}")
    @Transactional // 同时处理多个表，添加事务
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        // 首先判断用户有没有阅读该商品
        boolean isAdd = productReadService.addRead(new ProductRead(getLoginUser().getUserId(), id));
        if (isAdd) {
            // 需要将商品的阅读量+1
            productService.readNumPlusOne(id);
        }
        return success(productService.getById(id));
    }

    /**
     * 新增商品
     */
    @PreAuthorize("@ss.hasPermi('market:product:add')")
    @Log(title = "商品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Product product) {
        return toAjax(productService.insertProduct(product));
    }

    /**
     * 上传商品
     */
    @PreAuthorize("@ss.hasPermi('market:product:add')")
    @Log(title = "商品", businessType = BusinessType.INSERT)
    @PostMapping("/uploadSellProduct")
    // 因为操作了多个数据表，添加事务注解，要么都成功，要么都失败
    @Transactional
    public AjaxResult uploadSellProduct(@RequestBody ProductVo productVo) {
        /// 存储商品
        Product product = new Product();
        BeanUtils.copyProperties(productVo, product);

        if (product.getStatus() == 0) {
            //--if-- 如果是要发布商品，要先进行数据校验，确保商品的数据都是合法的
            LoginUser loginUser = getLoginUser();
            SysUser sysUser = userService.selectUserById(loginUser.getUserId());
            if (sysUser.getSchoolId() == null) {
                throw new ServiceException("请先前往'我的'页面中设置学校和校区，商品可以先保存草稿", ErrorCode.OPERATION_ERROR.getCode());
            }
            if (sysUser.getCampusId() == null) {
                throw new ServiceException("请先前往'我的'页面中设置校区，商品可以先保存草稿", ErrorCode.OPERATION_ERROR.getCode());
            }
            // 设置商品主人对应的学校和校区
            product.setSchoolId(sysUser.getSchoolId());
            product.setCampusId(sysUser.getCampusId());
            ProductValidate.validate(product);
            if (product.getId() == null) {
                // 设置商品主人
                product.setUserId(loginUser.getUserId());
                productService.insertProduct(product);
            } else {
                // 更新商品信息
                productService.updateProduct(product);
            }

            if (productVo.getPicList() == null || productVo.getPicList().size() == 0) {
                throw new ServiceException("商品没有上传对应的图片", ErrorCode.OPERATION_ERROR.getCode());
            }
        } else if (product.getStatus() == 3) {
            if (StringUtils.isEmpty(product.getName())) {
                throw new ServiceException("保存草稿时，商品名称不能为空", ErrorCode.OPERATION_ERROR.getCode());
            }

            //--if-- 如果只是保存草稿，不需要进行数据校验
            if (product.getId() == null) {
                // 设置商品主人
                product.setUserId(getLoginUser().getUserId());
                productService.insertProduct(product);
            } else {
                // 更新商品信息
                productService.updateProduct(product);
            }
        }

        /// 存储图片
        if (product.getId() != null) {
            // 先将商品绑定的图片删除
            pictureService.deletePicturesByItem(product.getId(), 0);
        }
        for (Picture picture : productVo.getPicList()) {
            picture.setItemId(product.getId());
            picture.setType(0);
        }
        if (productVo.getPicList().size() > 0) {
            pictureService.insertPictures(productVo.getPicList());
        }

        return AjaxResult.success();
    }

    /**
     * 修改商品
     */
    @PreAuthorize("@ss.hasPermi('market:product:edit')")
    @Log(title = "商品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Product product) {
        // 设置当前登录用户的用户id
        product.setUserId(getLoginUser().getUserId());
        if (product.getStatus() == 0) {
            // 如果想要将商品改成发布状态，需要对数据库的商品进行校验
            Product productInDatabase = productService.getById(product.getId());
            ProductValidate.validate(productInDatabase);
        }
        return toAjax(productService.updateProduct(product));
    }

    /**
     * 删除商品
     */
    @PreAuthorize("@ss.hasPermi('market:product:remove')")
    @Log(title = "商品", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(productService.deleteProductByIds(ids));
    }

}
